<?php
/**
 * 客户端 接口
 * 接口使用：https://gitee.com/inmad/paypal-hook/blob/master/README.md
 */

class PayPalClient
{
    private static $base_url = 'http://18.163.191.164/paypal-hook/';
    //错误记录
    private $error;

    private $sender_batch_header = [];
    private $items = [];
    
    public function __construct()
    {
    }

    public function checkIsSuc($res)
    {
        $result = true;
        //post请求异常抛出的错误
        if ($res === false) {
            $this->error = '返回无数据~';
            return false;
        }
        //接口返回信息
		if (is_string($res)) {
			$result = json_decode($res, true);
        }
        //https://developer.paypal.com/docs/api/reference/api-responses/#http-status-codes
		if (isset($result['error'])) {
            $this->error = $result;
            $result = false;
		}
		return $result;
    }

    // 获取错误记录
    public function getError()
    {
        return $this->error;
    }

    // batch id,每次提交时设置成唯一，30天内不能重复提交 最好与本地ID+time组合使用
    public function setSenderBatchId($sender_batch_id)
    {
        $this->sender_batch_header['sender_batch_id'] = $sender_batch_id;
        return $this;
    }

    // 邮件标题，
    public function setEmailSubject($email_subject)
    {
        $this->sender_batch_header['email_subject'] = $email_subject;
        return $this;
    }

    // 邮件内容
    public function setEmailMessage($email_message)
    {
        $this->sender_batch_header['email_message'] = $email_message;
        return $this;
    }

    /**
     * 转数组进来
     * @param srting recipient_type    EMAIL PHONE PAYPAL_ID
     * @param string amount[value]      支付价格，保留两位小数
     * @param string amount[currency]   货币类型 USD ...
     * @param string note              note 便笺
     * @param string receiver          收款人 recipient_type :EMAIL 这里写邮箱 | PAYPAL_ID 这里一申乱码
     * @param string sender_item_id     item编号 任意写，最好与本地ID关联
     */
    public function setItems($item)
    {
        //array_push($this->items, $item);
        $this->items[] = $item;
        return $this;
    }

    /**
     * Create batch payout
     */
    public function payouts()
    {
        $url = self::$base_url . 'payouts.php';

        if(empty($this->sender_batch_header['sender_batch_id'])) {
            $this->error = '缺少sender_batch_id参数';
            return false;
        }
        if(empty($this->sender_batch_header['email_subject'])) {
            $this->sender_batch_header['email_subject'] = 'You have a payout!';
        }
        if(empty($this->sender_batch_header['email_message'])) {
            $this->sender_batch_header['email_message'] = 'You have received a payout! Thanks for using our service!';
        }

        if(empty($this->items)) {
            $this->error = '缺少items参数';
            return false;
        }
        // foreach($this->items as $item) {
        //     if(empty($item['recipient_type']) || empty($item['amount']['value']) || empty($item['receiver'] || empty($item['sender_item_id'])) {
        //         $this->error = '缺少items参数~';
        //         return false;
        //     }
        // }

        $body = [
            'sender_batch_header' => $this->sender_batch_header,
            'items' => $this->items,
        ];
        $res = $this->post($url, json_encode($body));
        return $this->checkIsSuc($res);
    }

    /**
     * Show payout batch details
     */
    public function PayoutDetails($payout_batch_id)
    {
        $url = self::$base_url . 'payouts-details.php';

        if(empty($payout_batch_id)) {
            $this->error = '缺少payout_batch_id参数';
            return false;
        }
        
        $body = [
            'payout_batch_id' => $payout_batch_id,
        ];
        $res = $this->post($url, json_encode($body));
        return $this->checkIsSuc($res);
    }

    /**
     * Show payout item details
     */
    public function PayoutItemDetails($payout_item_id)
    {
        $url = self::$base_url . 'payouts-item-details.php';

        if(empty($payout_item_id)) {
            $this->error = '缺少payout_item_id参数';
            return false;
        }
        
        $body = [
            'payout_item_id' => $payout_item_id,
        ];
        $res = $this->post($url, json_encode($body));
        return $this->checkIsSuc($res);
    }

    /**
     * Cancel unclaimed payout item
     */
    public function PayoutItemCancel($payout_item_id)
    {
        $url = self::$base_url . 'payouts-item-cancel.php';

        if(empty($payout_item_id)) {
            $this->error = '缺少payout_item_id参数';
            return false;
        }
        
        $body = [
            'payout_item_id' => $payout_item_id,
        ];
        $res = $this->post($url, json_encode($body));
        return $this->checkIsSuc($res);
    }

    /**
     * $url string
     * $data json
     */
    private function post($url, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        # curl_setopt( $ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]); 

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        try {
            $res = curl_exec($ch);
        } catch (Exception $e) {
            $this->error = curl_error($ch);
            $res = false;
        }finally {
            curl_close($ch);
        }
        return $res;
    }
}
